import { localShoppingData, tempData } from '@/views/ShoppingCart/LocalShoppingData.ts'
import CommonModal from '@/views/ShoppingCart/components/CommonEditModal.tsx'
import { forwardRef, useEffect, useState } from 'react'
import { DeleteFilled } from '@ant-design/icons'
import { Button, Checkbox, Select } from 'antd'
import { getParkList } from '@/api/shoppingCart.ts'
import { message } from '@hs-admin/utils'
import { commonSelectProps } from '@/views/ShoppingCart/commonProps.ts'

const EditParkScope = forwardRef((props: { itemId: string; done: (() => void) | undefined; disabled?: boolean }, ref) => {
  const notEditable = !!props.disabled

  const haveCommon = !!localShoppingData('common')

  const [parkOptions, setParkOptions] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const searchPark = (word?: string) => {
    getParkList({
      keyword: word
    }).then((res) => {
      setParkOptions(
        (res.items ?? []).map((item: any) => ({
          label: item.park_name,
          value: item.id
        }))
      )
    })
  }

  const [isChoosing, setIsChoosing] = useState(false)

  const [parkList, setParkList] = useState<
    Array<{
      label: string
      value: string
    }>
  >([])

  const [useParent, setUseParent] = useState(false)

  const [parkValue, setParkValue] = useState<null | {
    label: string
    value: string
  }>(null)

  useEffect(() => {
    let data = localShoppingData(props.itemId, 'parkList') ?? []
    if (props.itemId !== 'common') {
      data = tempData('parkList') ?? []
      const useP3 = tempData('p3') ?? false
      setUseParent(useP3)
    } else {
      setUseParent(false)
    }
    setParkList(data)
  }, [props.itemId])

  return (
    <CommonModal
      ref={ref}
      title="园区范围选择"
      onOk={() => {
        if (notEditable) return
        props.done?.()
        if (props.itemId === 'common') {
          localShoppingData(props.itemId, { parkList })
        } else {
          tempData({ parkList })
          tempData({
            p3: useParent
          })
        }
      }}
      onCancel={() => {
        console.log('取消')
      }}>
      <div className="flex flex-col gap-4 max-h-70vh">
        {props.itemId !== 'common' && haveCommon && (
          <div>
            <Checkbox
              checked={useParent}
              onChange={(e) => {
                setUseParent(e.target.checked)
                if (e.target.checked) {
                  setParkList([])
                }
              }}>
              使用整体范围
            </Checkbox>
          </div>
        )}

        {!useParent && (
          <>
            {parkList.map((park) => (
              <div key={park.value} className="grid grid-cols-24">
                <div className="col-span-23 grid grid-cols-24 gap-1">
                  <span className="col-span-24 font-900">{park.label}</span>
                  <span className="col-span-20"> ID:{park.value}</span>
                </div>
                {!notEditable && (
                  <DeleteFilled
                    className="justify-self-end"
                    onClick={() => {
                      setParkList((prevState) => prevState.filter((it) => it.value !== park.value))
                    }}
                  />
                )}
              </div>
            ))}
            {isChoosing ? (
              <div className="flex gap-4">
                <Select
                  className="flex-1"
                  showSearch
                  {...commonSelectProps}
                  onSearch={searchPark}
                  onFocus={() => searchPark()}
                  value={parkValue?.value}
                  onChange={(_, option) => {
                    setParkValue(option)
                  }}
                  options={parkOptions}></Select>
                <Button
                  type="primary"
                  onClick={() => {
                    if (parkValue) {
                      if (parkList.some((item) => item.value === parkValue.value)) {
                        message.error('已存在')
                        return
                      }
                      setParkList((prevState) => [...prevState, parkValue])
                      setParkValue(null)
                      setIsChoosing(false)
                    }
                  }}>
                  确定
                </Button>
                <Button
                  onClick={() => {
                    setIsChoosing(false)
                  }}>
                  取消
                </Button>
              </div>
            ) : (
              !notEditable && (
                <Button type="primary" onClick={() => setIsChoosing(true)}>
                  + 添加园区
                </Button>
              )
            )}
          </>
        )}
      </div>
    </CommonModal>
  )
})

export default EditParkScope
